﻿function SearchForm(baseUrl, entityName, addImg, filter, pName, onselect)
{
    this.baseUrl = baseUrl;
    this.entityName = entityName;
    this.onselect = onselect;
    this.filter = filter || "";

    var title = "Select " + (pName || entityName);

    this.container = $(stringFormat("<div class='sf_outer' title='{0}'>\
                                        <input type='text' class='sf_nameFilter Inset'/>\
                                        <div class='sf_Table'></div>\
                                        <div class='ButtonRow'>\
                                            <div class='fl'><span class='Link Clear'>clear</span></div>\
                                            <div class='fr'>\
                                                <span class='Link Cancel'>cancel</span>\
                                                <input type='button' class='Select' value='Select'/>\
                                            </div>\
                                        </div>\
                                     </div>", title));
    

    var table = this;

    var width = Math.min(300, $(window).width() - 40),
    height = Math.min(460, $(window).height() - 60);
    var cont = this.container.dialog({
        height: height,
        width: width,
        modal: true,
        
        close: function ()
        {
            $(this).remove();
        }
    });

    $(".sf_outer .Cancel").click(function () { table.container.dialog("close"); });
    $(".sf_outer .Clear").click(function ()
    {
        table.container.dialog("close");
        if (onselect)
            onselect(null);
    });
    $(".sf_outer .Select").click(function ()
    {
        var val = table.val();
        table.container.dialog("close");
        if (onselect)
            onselect(val);
    });

    var cols = [];
    cols.push(new Column({
        name: "Name",
        getData: function (item)
        {
            var cb = stringFormat("<input type='checkbox' class='cbSearch'/>");
            var img = stringFormat("<img src='{0}/images/icon{1}.jpg'/>", baseUrl, entityName);
            return cb + (addImg? img: "") + item.Name;
        }
    }));

    var checkCB = function (cb)
    {
        $('.cbSearch').attr('checked', false);
        cb.attr('checked', true);
    }

    $('.sf_Table').clarizen_table({
        cols: cols,
        page: function (page, callback)
        {
            table.load(page, callback);
        },
        width: width - 50,
        height: height - 180,
        elements: [],
        baseUrl: baseUrl,
        beforeCellClick: function ()
        {
            checkCB($(this).closest('tr').find('input'));
        }
    });

    $('.sf_nameFilter').keyup(function ()
    {
        var timeout = 400;
        var filter = $(this);
        var value = filter.val();
        if ($('.sf_nameFilter').data('lastValue') == value)
            return;
        $('.sf_nameFilter').data('lastValue', value);
        window.setTimeout(function ()
        {
            if (filter.val() == value)
                table.load(0);
        }, timeout);
    });
    $('.sf_nameFilter').waterMark().blur();

    this.load = function (page, callback)
    {
        var that = this;
        if (page === 0)
            $('.sf_Table').clarizen_table('showLoading');

        this.load.count = this.load.count ? this.load.count + 1 : 1;
        var count = this.load.count;
        callback = callback || function (elements, totalCount)
        {
            $('.sf_Table').clarizen_table('reload', elements, totalCount);
        };


        var filter = $('.sf_nameFilter').val();
        var thisTable = this;
        remoteRequest({
            url: stringFormat("{0}/Entities/Search?name={1}&q={2}&page={3}&filter={4}", this.baseUrl, this.entityName, filter || "", page, this.filter),
            contentType: "JSON",
            type: "POST",
            success: function (data)
            {
                if (count != that.load.count)
                    return;
                $('.sf_Table').clarizen_table('enablePaging', data.Data.HasMore);
                callback(data.Data.Elements, data.Data.total);
            }
        });
    };

    this.val = function ()
    {
        var el = $('.sf_Table').clarizen_table('getSelectedElement');
        return { id: el.ID.Value, name: el.Name, typeName: el.ID.TypeName };
    }
} //task display

//$.fn.searchForm = function (options)
//{
//    var that = this;
//    that.ddl({events:false,className:options.className});
//    
//    this.ddl('ddlEl').click(function ()
//    {
//        new SearchForm(options.baseUrl, options.type, options.addImg, options.filter, options.pName, function (val)
//        {
//            that.html(stringFormat("<option value='{0}'>{1}</option>", val && val.id ? val.id : "", val && val.name ? val.name : "Select " + options.type))
//            that.change();
//            
//            that.ddl('set',{text:val? val.name: "Select " + options.type});
//            if (options.onselect)
//                options.onselect(val);
//            
//        }).load(0);
//    });
//    this.ddl('set', {text:this.find(":selected").html()});
//}



var searchForm = {
    _init: function ()
    {
        var that = this;
        var options = this.options;
        this.element.ddl({ events: false, className: options.className });

        this.element.ddl('ddlEl').click(function ()
        {
            if (!that.options.disabled)
                new SearchForm(options.baseUrl, options.type, options.addImg, options.filter, options.pName, function (val)
                {
                    that.element.html(stringFormat("<option value='{0}'>{1}</option>", val && val.id ? val.id : "", val && val.name ? val.name : "Select " + options.type))
                    that.element.change();

                    that.element.ddl('set', { text: val ? val.name : "Select " + options.type });
                    if (options.onselect)
                        options.onselect(val);

                }).load(0);
        });
        this.element.ddl('set', { text: this.element.find(":selected").html() });
    },

    options:
    {
        disabled: false
    },

    disable: function (disable)
    {
        this.options.disabled = disable;
    }
};

$.widget("ui.searchForm", searchForm);
